package com.java9s.goldchit.dao;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.EntityMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import com.java9s.goldchit.beans.GoldRate;

public class GoldRateDaoImpl implements GoldRateDao {

	private SessionFactory sessionFactory;
	private Session session;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public GoldRate getGoldRate(Date date) {
		GoldRate goldRate = null;
		session = getSessionFactory().openSession();
		Criteria criteria = session.createCriteria(GoldRate.class);
		criteria.add(Restrictions.eq("goldRateDate", date));
		List goldRateList = criteria.list();
		if (goldRateList != null && goldRateList.size() > 0) {
			goldRate = (GoldRate) goldRateList.get(0);
		}

		return goldRate;
	}

	@Override
	public List<GoldRate> getAllGoldRates() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void saveGoldRate(GoldRate goldRate) {
		session = getSessionFactory().openSession();
		if (goldRate != null) {
			session.clear();
			session.save(goldRate);
			session.flush();
		}
		// transaction.commit();
		session.close();

	}

	@Override
	public void updateGoldRate(GoldRate goldRate) {
		session = getSessionFactory().openSession();
		// Transaction transaction = session.beginTransaction();
		if (goldRate != null) {
			session.clear();
			session.update(goldRate);
			session.flush();
		}
		// transaction.commit();
		session.close();
	}

}
